<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<div style="padding: 10px">
    <h2>派车单列表</h2>
    <div style="margin:20px 0;">
        <table class="easyui-datagrid" id="departure-list-grid"
               data-options="singleSelect:true,collapsible:true,pagination:true">
        </table>
    </div>
    <div id="departure-driver-dialog" class="easyui-dialog"
         data-options="closed:true,modal: true"
         style="width:400px;padding:5px;">
        <form id="choose-driver-form" class="easyui-form" method="post"
              data-options="novalidate:true,ajax:true">
            <table>
                <tr>
                    <td style="font-size: 0.8rem;">选择司机：</td>
                    <td><select id="sales-selector" class="easyui-combobox" style="width:253px;;"
                                name="driverId"
                                data-options="required:true,missingMessage:'必须选择分配该派车单的司机'">
                        <option value=""></option>
                        <c:if test="${ not empty drivers}">
                            <c:forEach items="${drivers}" var="drivers">
                                <option value="${drivers.userId}">${drivers.userRealName}[${drivers.userLoginName}]</option>
                            </c:forEach>
                        </c:if>
                    </select>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <input type="hidden" name="X_Requested_With" value="XMLHttpRequest">
                        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitChangeDriver()">变更</a>
                    </td>
                </tr>
            </table>
        </form>
    </div>
    <script>
        var role = '${role}';
        if (role == '') {
            if ($ || $.messager) {
                $.messager.alert('错误！', '不能查看派车单信息', 'error')
            } else {
                alert("不能查看派车单信息");
            }
        }
        var editDriverForm = $('#choose-driver-form');
        var changeDriverDialog = $('#departure-driver-dialog');
        var departureGrid = $('#departure-list-grid');
        var toolbar = [{
            text: '更换司机',
            handler: function () {
                getSelectDeparture(function (row) {
                    if (row.departureStatus > 0) {
                        $.messager.alert("更换司机", "选中的派车单司机已接单,无法更换司机", 'info');
                        return;
                    }
                    var id = row.departureId;
                    editDriverForm.form({
                        url: window.projectPath + '/departure/' + id + '/dispense',
                        success: function (data) {
                            data = $.parseJSON(data);
                            $.messager.progress('close');
                            if (!data.error) {
                                $.messager.alert('变更派车单[id=' + id + ']司机', data.msg, 'info', function () {
                                    changeDriverDialog.dialog('close');
                                    departureGrid.datagrid("reload");
                                });
                            } else {
                                $.messager.alert('变更派车单[id=' + id + ']]司机', data.msg, "error");
                            }
                        }, onLoadError: function () {
                            $.messager.progress('close');
                        },
                        onSubmit: function (param) {
                            var isOk = $(this).form('enableValidation').form('validate');
                            if (isOk) {
                                $.messager.progress({
                                    title: '请稍候',
                                    msg: '变更派车单司机中...'
                                });
                            }
                            return isOk;
                        }
                    });
                    editDriverForm.form('load', {
                        driverId: row.departureDriverId
                    });
                    changeDriverDialog.dialog({
                        title: '变更派车单[' + id + ']司机'
                    });
                    changeDriverDialog.dialog('open');
                })
            }
        }, '-', {
            text: '司机确认接单',
            handler: function () {
                getSelectDeparture(function (row) {
                    if (row.departureStatus > 0) {
                        $.messager.alert("确认司机接单", "选中的派车单司机已接单", 'info');
                        return;
                    }
                    $.messager.confirm("派车单[id=" + row.departureId + "]确认司机接单", "是否已确认司机接单？", function (r) {
                        if (r) {
                            $.ajax({
                                url: window.projectPath + '/departure/' + row.departureId + '/make-receipt',
                                method: 'post',
                                success: function (res) {
                                    res = typeof res == 'string' ? $.parseJSON(res) : res;
                                    if (!res.error) {
                                        $.messager.alert("确认司机接单", res.msg, 'info');
                                        departureGrid.datagrid("reload");
                                    } else {
                                        $.messager.alert("确认司机接单", res.msg, 'error');
                                    }
                                }
                            });
                        }
                    });
                });
            }
        }, '-', {
            text: '开始发车',
            handler: function () {
                getSelectDeparture(function (row) {
                    if (row.departureStatus != 1) {
                        $.messager.alert("派车单[id=" + row.departureId + "]发车", "选中的派车单司机尚未接单或已发车", 'info');
                        return;
                    }
                    $.messager.confirm("派车单[id=" + row.departureId + "]开始发车", "是否已确认开始发车？", function (r) {
                        if (r) {
                            $.ajax({
                                url: window.projectPath + '/departure/' + row.departureId + '/departing',
                                method: 'post',
                                success: function (res) {
                                    res = typeof res == 'string' ? $.parseJSON(res) : res;
                                    if (!res.error) {
                                        $.messager.alert("确认司机开始发车", res.msg, 'info');
                                        departureGrid.datagrid("reload");
                                    } else {
                                        $.messager.alert("确认司机开始发车", res.msg, 'error');
                                    }
                                }
                            });
                        }
                    });
                });
            }
        }, '-', {
            text: '回厂收货',
            handler: function () {
                getSelectDeparture(function (row) {
                    if (row.departureStatus != 2) {
                        $.messager.alert("派车单[id=" + row.departureId + "]回厂收货", "选中的派车单尚未发车或已经处于回厂收货状态", 'info');
                        return;
                    }
                    $.messager.prompt('派车单[id=' + row.departureId + ']回厂收货', '请输入收货人姓名（称呼）：', function (name) {
                        if (!name) {
                            $.messager.alert("确认回厂收货", "回厂收货人不能为空", 'error');
                            return;
                        }
                        $.messager.confirm("派车单[id=" + row.departureId + "]回厂收货", "是否已确认回厂收货并且收货人为：" + name + "？", function (r) {
                            if (r) {
                                $.ajax({
                                    url: window.projectPath + '/departure/' + row.departureId + '/receive?receiverName=' + name,
                                    method: 'post',
                                    success: function (res) {
                                        res = typeof res == 'string' ? $.parseJSON(res) : res;
                                        if (!res.error) {
                                            $.messager.alert("确认回厂收货", res.msg, 'info');
                                            departureGrid.datagrid("reload");
                                        } else {
                                            $.messager.alert("确认回厂收货", res.msg, 'error');
                                        }
                                    }
                                });
                            }
                        });
                    })
                });
            }
        }, '-', {
            text: '查看详情',
            handler: function () {
                getSelectDeparture(function (row) {
                    window.turnTap('departureDetail', row.departureId);
                });
            }
        }, '-', {
            text: '下载详情文档（供打印）',
            handler: function () {
                getSelectDeparture(function (row) {
                    window.open(window.projectPath + '/departure/' + row.departureId + "/detail.doc");
                });
            }
        }, '-', {
            text: '删除',
            handler: function () {
                getSelectDeparture(function (row) {
                    $.messager.confirm("删除派车单[id=" + row.departureId + "]", "是否已确认删除该派车单？", function (r) {
                        if (r) {
                            $.ajax({
                                url: window.projectPath + '/departure/' + row.departureId + '/delete',
                                method: 'post',
                                success: function (res) {
                                    res = typeof res == 'string' ? $.parseJSON(res) : res;
                                    if (!res.error) {
                                        $.messager.alert("删除派车单[id=" + row.departureId + "]", res.msg, 'info');
                                        departureGrid.datagrid("reload");
                                    } else {
                                        $.messager.alert("删除派车单[id=" + row.departureId + "]", res.msg, 'error');
                                    }
                                }
                            });
                        }
                    });
                })
            }
        }, '-'];
        if (role == 'driver') {
            toolbar = [{
                text: '确认接单',
                handler: function () {
                    getSelectDeparture(function (row) {
                        if (row.departureStatus > 0) {
                            $.messager.alert("确认司机接单", "选中的派车单司机已接单", 'info');
                            return;
                        }
                        $.messager.confirm("派车单[id=" + row.departureId + "]确认司机接单", "是否已确认司机接单？", function (r) {
                            if (r) {
                                $.ajax({
                                    url: window.projectPath + '/departure/' + row.departureId + '/make-receipt',
                                    method: 'post',
                                    success: function (res) {
                                        res = typeof res == 'string' ? $.parseJSON(res) : res;
                                        if (!res.error) {
                                            $.messager.alert("确认司机接单", res.msg, 'info');
                                            departureGrid.datagrid("reload");
                                        } else {
                                            $.messager.alert("确认司机接单", res.msg, 'error');
                                        }
                                    }
                                });
                            }
                        });
                    });
                }
            }, '-', {
                text: '填写超时原因',
                handler: function () {
                    getSelectDeparture(function (row) {
                        if (row.departureRealCostTime == null) {
                            $.messager.alert("填写超时原因", "该派车单尚未完成，无法进行该操作", 'info');
                            return;
                        }
                        if (row.departureCostTime - row.departureRealCostTime >= 0) {
                            $.messager.alert("填写超时原因", "该派车单未超时，不用填写超时原因", 'info');
                            return;
                        }
                        $.messager.prompt("派车单[id=" + row.departureId + "]填写超时原因", "请填写您对于该派车单的超时原因:", function (r) {
                            if (r) {
                                $.ajax({
                                    url: window.projectPath + '/departure/' + row.departureId + '/fill-result',
                                    method: 'post',
                                    data: {result: r},
                                    success: function (res) {
                                        res = typeof res == 'string' ? $.parseJSON(res) : res;
                                        if (!res.error) {
                                            $.messager.alert("派车单[id=" + row.departureId + "]填写超时原因", res.msg, 'info');
                                            departureGrid.datagrid("reload");
                                        } else {
                                            $.messager.alert("派车单[id=" + row.departureId + "]填写超时原因", res.msg, 'error');
                                        }
                                    }
                                });
                            }
                        });
                    });
                }
            }, '-', {
                text: '查看详情',
                handler: function () {
                    getSelectDeparture(function (row) {
                        window.turnTap('departureDetail', row.departureId);
                    });
                }
            }, '-', {
                text: '下载详情文档（供打印）',
                handler: function () {
                    getSelectDeparture(function (row) {
                        window.open(window.projectPath + '/departure/' + row.departureId + "/detail.doc");
                    });
                }
            }];
        }
        /**
         * 更改司机的方法
         */
        function submitChangeDriver() {
            editDriverForm.submit();
        }
        /**
         * 获取选中的车单
         */
        function getSelectDeparture(cb) {
            var row = departureGrid.datagrid("getSelected");
            if (!row) {
                $.messager.alert("执行派车单的操作", "请先选中您想操作的派车单！", "info");
                return;
            }
            if (cb) {
                cb.call(window, row);
            }
        }
        departureGrid.datagrid({
            url: window.projectPath + "/departure/" + role + "/list",
            method: 'get',
            toolbar: toolbar,
            loadFilter: function (data) {
                // console.log(data);
                var result = {
                    rows: [],
                    total: 0
                };
                if (!data.error) {
                    result.total = data.pageInfo.total;
                    result.rows = data.pageInfo.list;
                } else {
                    $.messager.alert('加载错误', '加载派车单列表出错!' + data.msg, 'error');
                }
                departureGrid.innerRows = result;
                return result;
            },
            columns: [[
                {field: 'departureId', title: 'id'},

                {
                    field: 'departureInitiator', title: '车单发起者',
                    formatter: function (value, row, index) {
                        return value.userRealName + '[' + value.userLoginName + ']'
                    }
                },
                {
                    field: 'departureDriver', title: '当前司机',
                    formatter: function (value, row, index) {
                        return value.userRealName + '[' + value.userLoginName + ']'
                    }
                },
                {field: 'departureAimPlace', title: '派车目的地'},
                {field: 'departureTransition', title: '派车转场'},
                {
                    field: 'departureCostTime', title: '预计派车耗时（h）',
                    formatter: function (value, row, index) {
                        if (value == null) {
                            return '';
                        }
                        return Number.prototype.toFixed.call(value, 2);
                    }
                },
                {
                    field: 'departureRealCostTime', title: '实际派车耗时（h）',
                    formatter: function (value, row, index) {
                        if (value == null) {
                            return '';
                        }
                        return Number.prototype.toFixed.call(value, 2);
                    }
                },
                {
                    field: 'departureCostMoney', title: '预计派车经费（￥）',
                    formatter: function (value, row, index) {
                        if (value == null) {
                            return '';
                        }
                        return Number.prototype.toFixed.call(value, 2);
                    }
                },
                {
                    field: 'isOverTime', title: '是否超时',
                    formatter: function (value, row, index) {
                        if (row.departureRealCostTime != null) {
                            return row.departureCostTime - row.departureRealCostTime >= 0 ? '否' : '是';
                        } else {
                            return '该派车单尚未完成';
                        }
                    }
                },
                {
                    field: 'departureStatus', title: '派车单状态',
                    formatter: function (value, row, index) {
                        switch (value) {
                            case 0:
                                return '司机尚未接单';
                            case 1:
                                return '司机已接单';
                            case 2:
                                return '司机已发车';
                            case 3:
                                return '已到货';
                            default :
                                return '未知状态';
                        }
                    }
                }
            ]]
        });
    </script>
</div>